<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主体区域 -->
    <el-card>
      <!-- 按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 内容表格 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbuttom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级 -->
              <el-col :span="5">
                <el-tag closable @close="removeRigesById(scope.row, item1.id)">
                  {{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级 -->
              <el-col :span="19">
                <!-- for 嵌套 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRigesById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="13">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRigesById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <!-- 操作表格区 -->
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="addModification(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="removeEvent(scope.row.id)"
            ></el-button>
            <!-- 分配权限 -->
            <el-button
              type="warning"
              icon="el-icon-s-tools"
              @click="showSetRolesDialog(scope.row)"
            >
              分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑框 -->
    <el-dialog
      title="编辑"
      :visible.sync="setRolesDialogVisible"
      width="50%"
      @close="setRightDialogClose"
    >
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allitRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色文本框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      @close="addRolesClase"
    >
      <!-- 主体内容 -->
      <el-form
        :rules="editForm"
        ref="addRolesFromRef"
        :model="addRolesFrom"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改数据 -->
    <el-dialog title="提示" :visible.sync="addRolesVisible" width="30%">
      <!-- 中间数据 -->
      <el-form
        :model="editForm"
        :rules="addRolesFromRules"
        ref="rolesListRef"
        label-width="90px"
      >
        <el-form-item label="角色名称">
          <el-input v-model="editForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 存放数据
      rolesList: [],
      //   编辑框的状态
      setRolesDialogVisible: false,
      rightslist: [], //所有权限列表 的存储信息
      //   树形控件数据绑定
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      //存储三级标签的数组
      defKeys: [],
      //   当前即将分配id的角色
      roleId: '',
      addRolesDialogVisible: false,
      addRolesVisible: false,
      addRolesFrom: {
        roleName: '',
        roleDesc: '',
      },
      //查询到的放这里
      editForm: {},
      // 校验规则
      addRolesFromRules: {
        roleName: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
          },
          {
            min: 3,
            max: 10,
            message: '请输入3~10个字符之间',
            trigger: 'blur', //失去焦点
          },
        ],
        roleDesc: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
          },
          {
            min: 3,
            max: 10,
            message: '请输入3~10个字符之间',
            trigger: 'blur', //失去焦点
          },
        ],
      },
    }
  },
  created() {
    this.getrlesList()
  },
  methods: {
    // 获取用户列表
    async getrlesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 监听表单清空事件
    addRolesClase() {
      this.$refs.addRolesFromRef.resetFields()
    },
    // 添加角色
    addRoles() {
      this.$refs.addRolesFromRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) {
          return
        }
        // 到这里就可以发起post请求
        const { data: res } = await this.$http.post('roles', this.addRolesFrom)
        if (res.meta.message) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.getrlesList()
        this.addRolesDialogVisible = false
      })
    },
    // 1，根据id查询角色资料
    async addModification(id) {
      console.log(id)
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.$message.success('获取成功')
      this.editForm = res.data
      this.addRolesVisible = true
    },
    // 2.修改角色资料
    editUserInfo() {
      // 先获取验证对象
      this.$refs.rolesListRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        // 到这里已经验证成功
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          this.editForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更改失败')
        }
        this.$message.success('更改成功')
        this.addRolesVisible = false
        this.getrlesList()
      })
    },
    //删除角色
    async removeEvent(id) {
      // elemenet 弹窗
    //   console.log(id)
      const confirmRestult= await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch(err => err)
      console.log(confirmRestult)
      if(confirmRestult!='confirm'){
        return this.$message.info('取消了删除')
      }
      // 请求方式delete
      const { data: res } = await this.$http.delete('roles/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
        this.$message.success('删除成功');
        // 重新渲染
        this.getrlesList();
    },

    // 根据id删除对应标签
    async removeRigesById(role, rolesid) {
      const confirmRiges = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) //捕获取消状态
      if (confirmRiges !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      //   console.log('确认了删除')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rolesid}}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }

      this.$message.success('删除成功~~~~~')

      // 重新渲染 会导致合上
      //   this.getrlesList()
      // 建议直接给 把参数给他
      role.children = res.data
    },

    // 展示分配权限的对话框
    async showSetRolesDialog(role) {
      this.roleId = role.id
      // 获取全部数据
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      // 获取成功
      this.$message.success('获取成功')
      // 把数据存储在rightslist
      this.rightslist = res.data
      //   调用递归函数getLeafKeys（）
      // role 数据  defKeys存储第三标签的数组
      this.getLeafKeys(role, this.defKeys)
      this.setRolesDialogVisible = true
    },
    // 获取三级节点的值 通过递归的形式
    getLeafKeys(node, arr) {
      if (!node.children) {
        //如果node中没有children属性 则是三级节点
        return arr.push(node.id) //添加到arr数组
      }

      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听编辑框的事件
    setRightDialogClose() {
      this.defKeys = []
    },
    // 点击角色分配权限
    async allitRights() {
      const keys = [
        //把勾中的全部数据放到啊一个keys数组
        // getCheckedKeys 勾住已选的子选框  getHalfCheckedKeys父选框
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      // 把拿到的keys数组进行，隔开开
      const idStr = keys.join(',')

      // 发起一个请求
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配失败')
      }
      this.$message.success('分配成功')
      this.getrlesList()
      this.setRolesDialogVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 15px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbuttom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
